package pp.gateway.domain.user;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import pp.gateway.domain.user.aggregation.repository.UserLogin;
import pp.gateway.domain.user.aggregation.entity.loginstrategy.AccountLoginStrategy;
import pp.gateway.domain.user.aggregation.entity.loginstrategy.TelephoneMsgLoginStrategy;
import pp.infrastructure.exception.PPException;
import pp.infrastructure.exception.PPExceptionInfo;
import pp.infrastructure.mysql.mapper.user.UserDO;
import pp.infrastructure.mysql.mapper.user.UserReader;

@Slf4j
@Repository
public class UserLoginRepository {

    @Autowired
    private UserReader userReader;

    public UserLogin loadByAccount(String account) {   // account 和 userId 一样，也是唯一参数，不可重复的。前端也确实可以拿得到
        UserDO record = userReader.getByAccount(account);
        if(record == null) {
            log.error("{}.{} --> {};", this.getClass().getName(), new Object(){}.getClass().getEnclosingMethod().getName()
                    , "根据账号查询 User，未找到对应用户，account = " + account);
            throw new PPException(PPExceptionInfo.GENERIC_SYSTEM_MYSQL_RECORD_NOT_EXIST);
        }
        UserLogin userLogin = new UserLogin(record.getId());
        // 没有使用懒加载，一次性加载了所有的登录策略
        // 原因是：本身在加载 UserLogin 聚合根时，就可以拿到登录策略的所有数据，就不需要懒加载
        userLogin.setAccountLoginStrategy(new AccountLoginStrategy(record.getAccount(), record.getPwd(), record.getName(), record.getImg()));
        userLogin.setTelephoneMsgLoginStrategy(new TelephoneMsgLoginStrategy(record.getTelephone()));
        return userLogin;
    }

}
